package com.snopy.concurrency.demo_threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.StringJoiner;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author snopy
 * @version 1.0.0
 * @classname LinkedBlockingQueueTest
 * @description
 * @email 77912204@qq.com
 * @date 2022/02/19 9:45
 */
@Slf4j
public class LinkedBlockingQueueTest {
    private static final LinkedBlockingQueue<Banana> lbq = new LinkedBlockingQueue<>();
    public static void main(String[] args) {
        //new Thread(new Producer(lbq)).start();
        new Thread(new Producer(lbq)).start();
        new Thread(new Consumer(lbq)).start();
        new Thread(new Consumer(lbq)).start();
    }
    static class Banana{
        String[] memory;
        Banana(){
            this.memory = new String[1000000000];
        }
    }
    static class Producer implements Runnable{
        LinkedBlockingQueue<Banana> lbq;
        Producer(LinkedBlockingQueue<Banana> lbq){
            this.lbq = lbq;
        }
        @Override
        public void run() {
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(3);
                    produce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        private void produce(){
            Banana banana = new Banana();
            try {
                lbq.put(banana);
                log.info("长出了一根香蕉->{}",banana);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    static class Consumer implements Runnable{
        LinkedBlockingQueue<Banana> lbq;
        Consumer(LinkedBlockingQueue<Banana> lbq){
            this.lbq = lbq;
        }
        @Override
        public void run() {
            while (true){
                consume();
            }
        }
        private void consume(){
            try {
                TimeUnit.SECONDS.sleep(2);
                Banana banana = lbq.take();
                log.info("消费香蕉一根->{}",banana);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
